package com.comsoftstar.nt5s.Activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hzc.imagepicker.SImagePicker;
import com.hzc.imagepicker.activity.PhotoPickerActivity;
import com.hzc.nt5s.IConstant;
import com.hzc.nt5s.R;
import com.hzc.nt5s.adapter.PickAdapter;
import com.hzc.nt5s.deviceManager.bean.User;
import com.hzc.nt5s.deviceManager.preference.PreferencesUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QualityActivity extends AppCompatActivity implements View.OnClickListener {


    public static final int REQUEST_CODE_IMAGE = 101;
    private JSONArray organization;
    private List<String> list_group;
    private Map<String, String> map;
    private String[] strs_group;
    private JSONArray standard;
    private List<String> list_standard;
    private Map<String, String> standardmap;
    private String[] strs_standard;
    private StringBuffer group = new StringBuffer(1000);
    private TextView tv_workgroup, tv_quality;
    private GridView gridView;
    private Button upload, tv_back, tv_save,btn_choice_regulations;
    private List<String> url = new ArrayList<>();
    private List<String> pickedlist = new ArrayList<>();
    private boolean isShowDelete = false;
    private PickAdapter pickAdapter;
    private EditText et_standard, et_cardNum;
    private RelativeLayout rl_workshop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quality);
        initUI();
        setup();
    }


    private void initUI() {
        list_group = new ArrayList<>();
        list_standard = new ArrayList<>();
        map = new HashMap<>();
        standardmap = new HashMap<>();
        tv_workgroup = (TextView) findViewById(R.id.tv_group_quality);
        rl_workshop = (RelativeLayout) findViewById(R.id.rl_workshop);

//        tv_quality = (TextView) findViewById(R.id.tv_regulation);
        tv_back = (Button) findViewById(R.id.tv_back_quality);
        tv_save = (Button) findViewById(R.id.tv_save_quality);
        upload = (Button) findViewById(R.id.btn_upload_quality);
        pickAdapter = new PickAdapter(QualityActivity.this);
        gridView = (GridView) findViewById(R.id.view_pic);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                seeBig(url, i);
            }
        });
        et_standard = (EditText) findViewById(R.id.editText1);
        et_cardNum = (EditText) findViewById(R.id.editText2);
        btn_choice_regulations=(Button)findViewById(R.id.btn_choice_regulations);

    }

    private void setup() {
//        getOrganization();
//        new Thread() {
//            public void run() {
//                try {
//                    Thread.sleep(500);
//                } catch (InterruptedException e) {
//                    // Auto-generated catch block
//                    e.printStackTrace();
//                }
//                getQualityStandard();
//            }
//        }.start();
        getQualityOrganization();
//        getQualityStandard();
//        tv_quality.setOnClickListener(this);
        tv_workgroup.setOnClickListener(this);
        rl_workshop.setOnClickListener(this);
        tv_back.setOnClickListener(this);
        tv_save.setOnClickListener(this);
        upload.setOnClickListener(this);
        btn_choice_regulations.setOnClickListener(this);
    }



    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }

        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    private void showWorkShopDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("车间组别");
        group.delete(0, group.length());

        builder.setMultiChoiceItems(strs_group, null, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {

                if (isChecked) {
                    group.append(strs_group[which] + ",");
                }

            }

        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tv_workgroup.setText(group.deleteCharAt(group.length() - 1).toString());
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }

//    private void showStandardDialog() {
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setTitle("条例项目");
//
//        builder.setItems(strs_standard, new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                tv_quality.setText(strs_standard[which]);
//            }
//        });
//        builder.show();
//    }


    private void getQualityOrganization() {
        RequestParams params = new RequestParams(IConstant.URL + "getOrganization");
        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                System.out.println("返回结果：" + result);
                try {
                    organization = new JSONArray(result);
                    for (int i = 0; i < organization.length(); i++) {
                        JSONObject jo = (JSONObject) organization.get(i);
                        list_group.add(jo.optString("DeptName"));
                        map.put(jo.optString("DeptName"), jo.optString("DeptNo"));
                    }
                    strs_group = (String[]) list_group.toArray(new String[0]);
                    System.out.println("部门名称" + strs_group);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

//    private void getQualityStandard() {
//        RequestParams params = new RequestParams(IConstant.URL + "getQualityStandard");
////        System.out.println("请求的URL：" + params.toString());
//        x.http().post(params, new Callback.CommonCallback<String>() {
//
//
//            @Override
//            public void onSuccess(String result) {
////                System.out.println("返回结果：" + result);
//                try {
//                    standard = new JSONArray(result);
//                    for (int i = 0; i < standard.length(); i++) {
//                        JSONObject jo = (JSONObject) standard.get(i);
//                        list_standard.add(jo.optString("RegulationNo") + "、" + jo.optString("Standard") + "     黄牌数（" + jo.optString("CardNum") + "）张");
//                        standardmap.put(jo.optString("RegulationNo"), jo.optString("Guid"));
//                    }
//                    strs_standard = (String[]) list_standard.toArray(new String[0]);
////                    System.out.println("部门名称" + strs_group);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onError(Throwable ex, boolean isOnCallback) {
//
//            }
//
//            @Override
//            public void onCancelled(CancelledException cex) {
//
//            }
//
//            @Override
//            public void onFinished() {
//
//            }
//        });
//    }

    private void delete(int position) {//删除选中项方法
        List<String> newList = new ArrayList<String>();
        if (isShowDelete) {
            pickedlist.remove(position);
        }
        newList.addAll(pickedlist);
        pickedlist.clear();
        pickedlist.addAll(newList);
        url.clear();
        url.addAll(newList);
    }

    public void seeBig(List<String> url, int position) {
        Intent intent = new Intent();
        intent.setClass(QualityActivity.this, BigImgActivity.class);
        intent.putExtra("url", url.get(position).toString());
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back_quality:
                finish();
                break;
            case R.id.tv_save_quality:
                if (TextUtils.isEmpty(et_standard.getText())) {
                    Toast.makeText(QualityActivity.this, "请输入被罚条例", Toast.LENGTH_LONG).show();
                } else if (TextUtils.isEmpty(et_cardNum.getText())) {
                    Toast.makeText(QualityActivity.this, "请输入黄牌数", Toast.LENGTH_LONG).show();
                } else {
                    SaveDialog();

                }
                break;
            case R.id.btn_upload_quality:
                SImagePicker
                        .from(QualityActivity.this)
                        .maxCount(9)
                        .rowCount(3)
                        .showCamera(true)
                        .pickMode(SImagePicker.MODE_IMAGE)
                        .forResult(REQUEST_CODE_IMAGE);
            case R.id.rl_workshop:

                showWorkShopDialog();
                break;
            case R.id.tv_group_quality:

                showWorkShopDialog();
                break;
//            case R.id.btn_choice_regulations:
//                Intent intent = new Intent(QualityActivity.this,QualityDirectAppraisalActivity.class);
//                startActivity(intent);
//                break;


        }
    }

    private void SaveDialog() {

        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("确定要保存？"); //设置内容
        builder.setIcon(R.mipmap.ic_launcher);//设置图标，图片id即可
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //关闭dialog

                RequestParams params = new RequestParams(IConstant.URL + "qualityReview");
                User user = PreferencesUtil.getUser(QualityActivity.this);
                params.addBodyParameter("UserName", user.getUserName());//文件后缀名(带点)
                params.addBodyParameter("CardNum", et_cardNum.getText().toString());
                params.addBodyParameter("SimpleRegulation", et_standard.getText().toString());
                map.put("请选择车间", "");
//                  params.addBodyParameter("groupName",tv_workgroup.getText().toString());

                StringBuffer stringBuffer = new StringBuffer(1000);

                for (int i = 0; i < tv_workgroup.getText().toString().split(",").length; i++) {
                    stringBuffer.append(map.get(tv_workgroup.getText().toString().split(",")[i]) + ",");
                }
                stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                params.addBodyParameter("WorkShop", stringBuffer.toString());
                if (pickedlist != null && !pickedlist.isEmpty()) {
                    List<KeyValue> list = new ArrayList<>();
                    for (int i = 0; i < pickedlist.size(); i++) {
                        list.add(new KeyValue("image" + i, new File(pickedlist.get(i))));
                        MultipartBody body = new MultipartBody(list, "UTF-8");
                        params.setRequestBody(body);
                    }
                }
                System.out.println("请求的URL：" + params.toString());
                x.http().post(params, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        System.out.println(result);
                        Toast.makeText(QualityActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                        finish();
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        System.out.println(ex);
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });


            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            final ArrayList<String> pathList =
                    data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);
            System.out.println("pathList" + pathList.toString());
            pickedlist.addAll(pathList);
            url.addAll(pickedlist);
            pickAdapter = new PickAdapter(QualityActivity.this);
            pickAdapter.setNewData(pickedlist);
            gridView.setAdapter(pickAdapter);
            isShowDelete = false;
            pickAdapter.setIsShowDelete(isShowDelete);
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    seeBig(url, i);
                }
            });
            gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if (isShowDelete) {
                        isShowDelete = false;
                    } else {
                        isShowDelete = true;
                        pickAdapter.setIsShowDelete(isShowDelete);
                        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                                delete(position);//删除选中项
                                pickAdapter = new PickAdapter(QualityActivity.this);//重新绑定一次adapter
                                pickAdapter.setNewData(pickedlist);
                                pickAdapter.setIsShowDelete(isShowDelete);
                                gridView.setAdapter(pickAdapter);
                            }
                        });
                    }
                    pickAdapter.setIsShowDelete(isShowDelete);//setIsShowDelete()方法用于传递isShowDelete值
                    return true;
                }
            });

        }
    }
}
